﻿using HamcoWcs.Contract.ContractCommon;
using HamcoWcs.DAL;
using HamcoWcs.Entitys.MainTaskBaks;
using HamcoWcs.Entitys.TaskAmounts;
using HamcoWcs.Models.Common.Enums;
using HamcoWcs.Service.Common;
using Quartz;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace HamcoWcs.Workers.AmountWorkers
{
    [AutoInject(typeof(IJob), InjectType.Worker)]
    [DisallowConcurrentExecution]
    public class ChartWorker : IJob
    {
        private readonly WcsDbContext _wcsDbContext;

        private readonly ILoggerService _loggerService;

        public ChartWorker(WcsDbContext wcsDbContext, ILoggerService loggerService)
        {
            _wcsDbContext = wcsDbContext;
            _loggerService = loggerService;
        }
        public Task Execute(IJobExecutionContext context)
        {
            try
            {
                CountTask();
            }
            catch (Exception e)
            {
                _loggerService.AddSystemErrorLog("AmountWorker:" + e.Message);
            }
            return Task.CompletedTask;

        }

        private void CountTask()
        {
            var Totallist = new List<MainTaskBak>();
            var Inboundlist = new List<MainTaskBak>();
            var Outboundlist = new List<MainTaskBak>();
            DateTime nowdata = Convert.ToDateTime(DateTime.Now);
            //总任务
            var TotalTasks = _wcsDbContext.MainTaskBaks
                 .Where(x => x.CreatedTime.AddDays(1) >= nowdata).ToList();
            if (TotalTasks.Count() == 0) return;
            foreach (var totaltask in TotalTasks)
            {
                Totallist.Add(totaltask);
            }
            var InboundTasks = TotalTasks.Where(x => x.MainTaskType == EnumMainTaskType.InboundTask.ToString()).ToList();
            var OutboundTasks = TotalTasks.Where(x => x.MainTaskType == EnumMainTaskType.OutboundTask.ToString()).ToList();
            foreach (var inboundtask in InboundTasks)
            {
                Inboundlist.Add(inboundtask);
            }
            foreach (var outboundtask in OutboundTasks)
            {
                Outboundlist.Add(outboundtask);
            }
            var taskAmount = new TaskAmount()
            {
                TotalTaskAmount = Totallist.Count().ToString(),
                InboundTaskAmount = Inboundlist.Count().ToString(),
                OutboundTaskAmount = Outboundlist.Count().ToString(),
                amount = Totallist.Count()
            };
            _wcsDbContext.Add(taskAmount);
            _wcsDbContext.SaveChanges();
        }
    }
}
